package com.mazaiting.common.core.utils;

import com.mazaiting.common.core.factory.NamedThreadFactory;

import java.util.concurrent.*;

/**
 * 线程池工具类
 *
 * @author mazaiting
 * @create_time 2022/9/5 12:27
 */
public class ThreadUtil {

    /**
     * 获取当前运行机器的可用CPU核心数
     */
    public final static int POLLER_THREAD_COUNT = Runtime.getRuntime().availableProcessors();

    /**
     * 自定义线程池
     * @param prefix 线程池名称前缀
     * @return 自定义线程池
     */
    public static ThreadPoolExecutor newExecutor(String prefix) {
        // 自定义线程池
        return newExecutor(new NamedThreadFactory(prefix));
    }


    /**
     * 自定义的线程池服务
     * @param threadFactory 线程池工程
     * @return 线程池服务
     */
    public static ThreadPoolExecutor newExecutor(ThreadFactory threadFactory) {
        // 自定义线程池
        return new ThreadPoolExecutor(
                POLLER_THREAD_COUNT,
                POLLER_THREAD_COUNT * 8,
                30L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(64),
                threadFactory,
                new ThreadPoolExecutor.CallerRunsPolicy());
    }
}
